﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="Question.cs" company="Rolosoft Ltd">
//   © Rolosoft Ltd
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

#region License

// Copyright 2013 Rolosoft Ltd
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion

namespace Rsft.Net.Dns.Entities
{
    #region Usings

    using System;
    using System.Collections.Generic;
    using System.Diagnostics.Contracts;
    using System.Globalization;
    using System.Net;
    using System.Text;

    using Rsft.Net.Dns.Interfaces;

    #endregion

    /// <summary>
    ///     The question.
    /// </summary>
    public sealed class Question
    {
        #region Fields

        /// <summary>
        ///     The q name.
        /// </summary>
        private string qname;

        #endregion

        #region Constructors and Destructors

        /// <summary>
        /// Initializes a new instance of the <see cref="Question"/> class.
        /// </summary>
        /// <param name="qname">
        /// The qname.
        /// </param>
        /// <param name="qClassType">
        /// Type of the q class.
        /// </param>
        /// <param name="qType">
        /// Type of the q.
        /// </param>
        public Question(string qname, QClassType qClassType, QType qType)
        {
            Contract.Requires(!string.IsNullOrEmpty(qname));

            this.qname = qname;
            this.QClassType = qClassType;
            this.QType = qType;
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="Question"/> class.
        /// </summary>
        /// <param name="recordReader">
        /// The record reader.
        /// </param>
        public Question(IRecordReader recordReader)
        {
            Contract.Requires(recordReader != null);

            this.QName = recordReader.ReadDomainName();
            this.QType = (QType)recordReader.ReadUInt16();
            this.QClassType = (QClassType)recordReader.ReadUInt16();
        }

        #endregion

        #region Public Properties

        /// <summary>
        ///     Gets or sets the data.
        /// </summary>
        /// <value>
        ///     The data.
        /// </value>
        public IList<byte> Data
        {
            get
            {
                var data = new List<byte>();
                data.AddRange(WriteName(this.QName));
                data.AddRange(WriteShort((ushort)this.QType));
                data.AddRange(WriteShort((ushort)this.QClassType));
                return data;
            }
        }

        /// <summary>
        ///     Gets QClass type.
        /// </summary>
        public QClassType QClassType { get; private set; }

        /// <summary>
        ///     Gets QName.
        /// </summary>
        public string QName
        {
            get
            {
                return this.qname;
            }

            private set
            {
                Contract.Requires(value != null);

                this.qname = value;
                if (!this.qname.EndsWith(".", StringComparison.OrdinalIgnoreCase))
                {
                    this.qname += ".";
                }
            }
        }

        /// <summary>
        ///     Gets QType.
        /// </summary>
        public QType QType { get; private set; }

        #endregion

        #region Public Methods and Operators

        /// <summary>
        ///     Returns a <see cref="System.String" /> that represents this instance.
        /// </summary>
        /// <returns>
        ///     A <see cref="System.String" /> that represents this instance.
        /// </returns>
        public override string ToString()
        {
            return string.Format(
                CultureInfo.InvariantCulture, "{0,-32}\t{1}\t{2}", this.QName, this.QClassType, this.QType);
        }

        #endregion

        #region Methods

        /// <summary>
        /// Writes the name.
        /// </summary>
        /// <param name="src">
        /// The SRC.
        /// </param>
        /// <returns>
        /// Various stuff.
        /// </returns>
        private static IEnumerable<byte> WriteName(string src)
        {
            Contract.Requires(!string.IsNullOrEmpty(src));

            if (!src.EndsWith(".", StringComparison.OrdinalIgnoreCase))
            {
                src += ".";
            }

            if (src == ".")
            {
                return new byte[1];
            }

            var sb = new StringBuilder();
            int intI, intJ, intLen = src.Length;
            sb.Append('\0');
            for (intI = 0, intJ = 0; intI < intLen; intI++, intJ++)
            {
                sb.Append(src[intI]);
                if (src[intI] == '.')
                {
                    var i = intI - intJ;

                    if (i < 0)
                    {
                        throw new InvalidOperationException("Negative boundary.");
                    }

                    sb[i] = (char)(intJ & 0xff);
                    intJ = -1;
                }
            }

            sb[sb.Length - 1] = '\0';
            return Encoding.ASCII.GetBytes(sb.ToString());
        }

        /// <summary>
        /// Writes the short.
        /// </summary>
        /// <param name="value">
        /// The s value.
        /// </param>
        /// <returns>
        /// Various stuff
        /// </returns>
        private static IEnumerable<byte> WriteShort(ushort value)
        {
            return BitConverter.GetBytes(IPAddress.HostToNetworkOrder((short)value));
        }

        #endregion
    }
}